/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月26日
 */
package com.massyframework.beanskin.runtime.framework;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleListener;
import com.massyframework.beanskin.framework.FrameworkConfig;
import com.massyframework.beanskin.framework.FrameworkEvent;
import com.massyframework.beanskin.framework.FrameworkListener;

/**
 * 支持事件监听的配置器
 * @author huangkh
 *
 */
public final class DefaultFrameworkConfig extends AttributeConfig 
	implements FrameworkConfig{
	
	private Logger logger = LoggerFactory.getLogger(DefaultFrameworkConfig.class);

	protected List<FrameworkListener> frameworkListeners;
	protected List<ModuleListener> moduleListeners;
	
	/**
	 * 
	 */
	public DefaultFrameworkConfig() {
		this.frameworkListeners = new CopyOnWriteArrayList<>();
		this.moduleListeners = new CopyOnWriteArrayList<>();
	}
	
	/**
	 * 添加运行框架事件监听器
	 * @param listener {@link FrameworkListener}
	 */
	public void addListener(FrameworkListener listener) {
		if (listener != null) {
			this.frameworkListeners.add(listener);
		}
	}
	
	@Override
	public void addListener(ModuleListener listener) {
		if (listener != null) {
			this.moduleListeners.add(listener);
		}
	}

	/**
	 * 移除运行框架事件监听器
	 * @param listener {@link FrameworkListener}
	 */
	public void removeListener(FrameworkListener listener) {
		if (listener != null) {
			this.frameworkListeners.remove(listener);
		}
	}
	
	@Override
	public void removeListener(ModuleListener listener) {
		if (listener != null) {
			this.moduleListeners.remove(listener);
		}	
	}

	/**
	 * 发布运行框架事件
	 * @param event {@link FrameworkEvent}
	 */
	public void applyEvent(FrameworkEvent event) {
		for (FrameworkListener listener: this.frameworkListeners) {
			try {
				listener.onEvent(event);
			}catch(Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}

	@Override
	public String toString() {
		return "DefaultFrameworkConfig";
	}
	
}
